package com.angel.bo.message.event;



import com.angel.bo.auth.client.jwt.AuthUtil;
import com.angel.bo.beans.jwt.JwtInfo;
import com.angel.bo.common.util.JsonUtil;
import com.angel.bo.message.session.SocketSessionRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;

import java.util.Map;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 14:27 2018/3/1
 */
@Slf4j
@Component
public class ConnectEventListener implements ApplicationListener<SessionConnectedEvent> {

	@Autowired
	private SocketSessionRegistry webAgentSessionRegistry;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private AuthUtil authUtil;

	@Override
	public void onApplicationEvent(SessionConnectedEvent sessionConnectedEvent) {


		StompHeaderAccessor sha = StompHeaderAccessor.wrap(sessionConnectedEvent.getMessage());
		//login get from browser
		MessageHeaderAccessor accessor = NativeMessageHeaderAccessor.getAccessor(sessionConnectedEvent.getMessage(), SimpMessageHeaderAccessor.class);
		accessor.getMessageHeaders();
		Object header = accessor.getHeader("simpConnectMessage");
		GenericMessage<?> generic = (GenericMessage<?>) accessor.getHeader("simpConnectMessage");
		Object nativeHeaders = generic.getHeaders().get("nativeHeaders");


		log.info(JsonUtil.toJson(nativeHeaders));
		String sessionId = sha.getSessionId();
		String token = ((Map)generic.getHeaders().get("nativeHeaders")).get("Authorization").toString();
		token = token.substring(1,token.length()-1);


		JwtInfo jwtInfo = null;
		try {
			jwtInfo = authUtil.getJwtFromToken(token);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		webAgentSessionRegistry.registerSessionId(jwtInfo.getUserId(), sessionId);
		log.info("{}-{}加入连接",jwtInfo.getUserId(),sessionId);
	}
}